// src/hooks/useFollowState.ts
import { useState, useCallback } from 'react';

export const useFollowState = () => {
  const [followCounts, setFollowCounts] = useState<{
    [userId: string]: { followCount: number; followerCount: number; mutualCount: number };
  }>({});

  // 更新特定用户的关注数量
  const updateFollowCounts = useCallback(async (userId: string) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return;

      let followCount = 0;
      let followerCount = 0;

      // 获取关注数量
      try {
        const followCountResponse = await fetch(`/api/userfollows/follower/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (followCountResponse.ok) {
          const data = await followCountResponse.json();
          followCount = typeof data === 'number' ? data : data.count || 0;
        }
      } catch (error) {
        console.error('获取关注数量失败:', error);
      }

      // 获取粉丝数量
      try {
        const followerCountResponse = await fetch(`/api/userfollows/followee/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (followerCountResponse.ok) {
          const data = await followerCountResponse.json();
          followerCount = typeof data === 'number' ? data : data.count || 0;
        }
      } catch (error) {
        console.error('获取粉丝数量失败:', error);
      }

      // 计算互关数量（简化处理）
      const mutualCount = Math.min(followCount, followerCount);

      setFollowCounts(prev => ({
        ...prev,
        [userId]: { followCount, followerCount, mutualCount }
      }));

    } catch (error) {
      console.error('更新关注数量失败:', error);
    }
  }, []);

  return {
    followCounts,
    updateFollowCounts
  };
};